package com.lanwf.admin.sys.login;

import com.jfinal.kit.Ret;
import com.lanwf.common.model.SysAdmin;
import com.lanwf.admin.utils.Cons;
import com.lanwf.admin.utils.TripleDes;

/**
 * @Auther: Lanwf
 * @Date: 2022/8/12 16:02
 * @Description:
 */
public class LoginService {

    public Ret doLogin(String username, String encryptText){

        String passwordText = TripleDes.decrypt3DES(encryptText, Cons.KEY);

        if(passwordText == null){
            return Ret.fail("账号或密码错误");
        }

        String password = passwordText.substring(0, passwordText.indexOf("#"));
        String expireDate = passwordText.substring(passwordText.indexOf("#") + 1);

        if(System.currentTimeMillis() > Long.valueOf(expireDate)){
            return Ret.fail("密码已过期,请重新登录!");
        }


        SysAdmin first = SysAdmin.dao.findFirst("select * from sys_admin where username = ? and password = ? ", username, password);
        if(first == null){
            SysAdmin sysAdmin = SysAdmin.dao.findFirst("select * from sys_admin where username = ?  ",username);
            if(sysAdmin != null){
                if(sysAdmin.getStatus() != null && sysAdmin.getStatus().intValue() == 1){
                    return Ret.fail("账号已被冻结");
                }

                sysAdmin.setErrorTime(sysAdmin.getErrorTime() == null ? 1 : sysAdmin.getErrorTime()+1);
                if(sysAdmin.getErrorTime() == 4 ){
                    sysAdmin.setStatus(1);
                }
                sysAdmin.update();
                if(sysAdmin.getErrorTime() >= 4){
                    return Ret.fail("账号已被冻结");
                }
                return Ret.fail("输入错误，您还有"+(4-sysAdmin.getErrorTime())+"次机会");
            }else{
                return Ret.fail("账号或密码错误");
            }
        }


        first.setErrorTime(0);
        first.update();
        return Ret.ok().set("password",password).set("username",username).set("id",first.getId());
    }
}
